package admin

import (
	"gitee.com/kordar/layuiadmin/admin/enums"
	"gitee.com/kordar/layuiadmin/admin/inject"
	ginsys_starter "github.com/kordar/ginsys-starter"
	"github.com/kordar/ginsys/resp"
	gocrudgorm "github.com/kordar/gocrud-gorm"
	goframeworkgormmysql "github.com/kordar/goframework-gorm-mysql"
	logger "github.com/kordar/gologger"
	"github.com/robfig/cron/v3"
	"github.com/spf13/cast"
)

type GoAdminModule struct {
	c *cron.Cron
}

func (m GoAdminModule) Depends() []string {
	return []string{"mysql"}
}

func (m GoAdminModule) Name() string {
	return "goadmin"
}

func (m GoAdminModule) Close() {
	m.c.Stop()
}

func (m GoAdminModule) Load(value interface{}) {

	mm := cast.ToStringMap(value)
	// 非租户模式，设置默认数据库为当前db
	db := cast.ToString(mm["db"])

	if !goframeworkgormmysql.HasMysqlInstance(db) {
		logger.Fatalf("[goadmin] 系统初始化失败，未查询到有效数据库实例-%s", db)
	}

	// 重置token秘钥
	hmacSampleSecret := cast.ToString(mm["hmac-sample-secret"])
	if hmacSampleSecret != "" && len(hmacSampleSecret) > 6 {
		enums.HmacSampleSecret = hmacSampleSecret
	}

	// 初始化crud组件
	gocrudgorm.InitExec()
	// 初始化crud多语言
	resp.InitCrudLangFn()

	resp.InitJsonResp001()
	if ginsys_starter.I18nEnabled {
		resp.InitI18nResponse()
	} else {
		resp.InitResponse002()
	}

	// 初始化数据提供者
	providers()
	invokes()
}

func providers() {
	inject.RepositoryProvider()
	inject.CaptchaProvider()
	inject.ControllerProvider()
	inject.ServiceProvider()
	inject.ValidatorProvider()
	// 注册路由
	routerProvider()
}

func invokes() {
	inject.ResourceServiceInvoke()
}
